package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Teacher;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;

public class OtherTeacherDao05 implements BaseTeacherDao {
    private static ArrayList<Teacher> teachers = new ArrayList<>();


    static {
        try {
            FileInputStream fis = new FileInputStream("itheima-edu-info-manager\\tea4.txt");
            int len;
            byte[] bytes = new byte[1024];
            String str = "";
            while ((len = fis.read(bytes)) != -1) {
                str += new String(bytes, 0, len);
            }
//            System.out.println(str);

            String[] split = str.split(System.lineSeparator());
            for (String s : split) {
                String[] split1 = s.split(",");
                Teacher teacher = new Teacher(split1[0], split1[1], split1[2], split1[3]);
                teachers.add(teacher);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean addTeacher(Teacher teacher) {
        boolean add = teachers.add(teacher);
        reSave();
        return add;

    }

    public Teacher[] findAllTeacher() {
        Teacher[] teacher = new Teacher[teachers.size()];
        for (int i = 0; i < teachers.size(); i++) {
            Teacher teacher1 = teachers.get(i);
            teacher[i] = teacher1;
        }
        return teacher;
    }

    public void deleteTeacher(String sid) {
        int index = getIndex(sid);
        teachers.remove(index);
        reSave();
    }


    public void updateTeacher(String sid, Teacher teacher) {
        int index = getIndex(sid);
        teachers.set(index, teacher);
        reSave();
    }


    public int getIndex(String sid) {
        int index = -1;
        Teacher[] t = new Teacher[teachers.size()];
        Teacher[] tea = OtherTeacherDao05.teachers.toArray(t);
        for (int i = 0; i < tea.length; i++) {
            Teacher teacher = tea[i];
            if (teacher != null && sid.equals(teacher.getSid())) {
                index = i;
            }
        }
        return index;
    }

    public void reSave() {
        try {

            FileOutputStream fos = new FileOutputStream("itheima-edu-info-manager\\tea4.txt");
            for (Teacher teacher : teachers) {
                fos.write(teacher.toString().getBytes());
                fos.write(System.lineSeparator().getBytes());
                fos.flush();
            }
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
